'''
Created on Dec 6, 2009

@author: bodnaria
'''
import os
import cgi
from google.appengine.ext.webapp import template
from util import AuthorizedPage
import hashlib
from model.Project import createProject
from error.UserError import UserError as UserError


class CreateProjectPage(AuthorizedPage):
    name = ""
    desc = ""
    
    def getIfAuthorized(self):
        errors = {'missingField' : "Please fill out all of the fields!",
                  'badProject' : "A project with the same name already exists!"}
        
        if self.error in errors.keys():
            error = errors[self.error]
        else:
                error = ""
                  
        self.outputHeader()
                  
        templatePath = os.path.join(os.path.dirname(__file__), 'create_project.html')
        self.response.out.write(template.render(templatePath , {"error": error,
                                                                "desc":self.desc, 
                                                                "name": self.name} )) 
    
    def postIfAuthorized(self):
        user = self.authorizedUser
        self.name = cgi.escape(self.request.get("nameproject"))
        self.desc = cgi.escape(self.request.get("desc"))
                
        hashed_url = "http://cs440x-bookbook.appspot.com/?project=" + hashlib.sha256(self.name).hexdigest()
        
        if self.name == "" or self.name =="" :
            self.error('missingField')
            self.getIfAuthorized()
            return
        else:
            try:
                createProject(self.name, 
                                        user.username,
                                        self.desc,
                                        hashed_url)
                self.redirect('/project=' + hashed_url)
                return
            except UserError :
                self.error('badProject')
                self.getIfAuthorized()
                return
  